package com.maker.ai.controller;

import com.maker.ai.aiservice.MakerChatService;
import com.maker.ai.service.OptRagService;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.parser.apache.tika.ApacheTikaDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.store.embedding.EmbeddingMatch;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

@RestController
public class ChatController {
    @Resource
    private OpenAiChatModel model;
    @Resource
    private EmbeddingModel embeddingModel;
    @Resource
    private MakerChatService makerChatService;
    @Resource
    private EmbeddingStore<TextSegment> embeddingStore;
    @Resource
    private OptRagService optRagService;


    @RequestMapping(value = "/chat", produces="text/html;charset=utf-8")
    public Flux<String> chat(String memoryId,String message){
        Flux<String> result = makerChatService.chat(memoryId,message);
        return result;
    }

    @GetMapping("/rag/add")
    public String ragAdd() throws FileNotFoundException {

        String filePath ="D:\\java_project\\langchain-demo\\src\\main\\resources\\爱康国宾体检中心体检项目表.pdf";
//        String filePath ="D:\\java_project\\langchain-demo\\src\\main\\resources\\堡垒机运维中工单号记录.docx";
//        Document document = new ApacheTikaDocumentParser().parse(fileInputStream);
//        //构建文档分割器对象
//        DocumentSplitter documentSplitter = DocumentSplitters.recursive(1000, 50);
//        //实现文本数据切割，向量化，存储
//        EmbeddingStoreIngestor ingestor =EmbeddingStoreIngestor.builder()
//                        .embeddingStore(embeddingStore)
//                        .documentSplitter(documentSplitter)
//                        .embeddingModel(embeddingModel)
//                        .build();
//        ingestor.ingest(document);
        String ragId =optRagService.ingestDocument(filePath);
        return "添加成功:"+ragId;

    }
    
    /**
     * 更新知识库中文档的内容
     * @param id 文档ID
     * @param filePath 新的内容
     * @return 操作结果
     */
    @PostMapping("/rag/update")
    public String ragUpdate(String id, String filePath) throws FileNotFoundException {
        //模拟 数据
        id="17";
        filePath ="D:\\java_project\\langchain-demo\\src\\main\\resources\\爱康国宾体检中心体检项目表.pdf";
        String newRagId =optRagService.updateDocument(id,filePath);
        return "更新成功:"+newRagId;
    }
    
    /**
     * 删除知识库中的文档
     * @param id 文档ID
     * @return 操作结果
     */
    @DeleteMapping("/rag/delete")
    public String ragDelete(String id) {
        // 从向量存储中删除指定ID的条目
//        embeddingStore.remove(id);
        return "删除成功";
    }
    
    /**
     * 删除所有知识库内容
     * @return 操作结果
     */
    @DeleteMapping("/rag/clear")
    public String ragClear() {
        // 清空整个向量存储
        embeddingStore.removeAll();
        return "已清空所有内容";
    }
    
    /**
     * 搜索知识库中的内容
     * @param query 查询内容
     * @return 匹配的结果
     */
    @GetMapping("/rag/search")
    public List<EmbeddingMatch<TextSegment>> ragSearch(@RequestParam String query) {
        // 为查询生成嵌入向量
        Response<Embedding> embeddingResponse = embeddingModel.embed(query);
        Embedding queryEmbedding = embeddingResponse.content();
        
        // 在向量存储中搜索相似内容
        EmbeddingSearchRequest request = EmbeddingSearchRequest.builder()
                .queryEmbedding(queryEmbedding)
                .maxResults(5)
                .minScore(0.5)
                .build();
                
        return embeddingStore.search(request).matches();
    }


//    @RequestMapping("/chat")
//    public String chat(String message){
//        String result = chatService.chat(message);
//        return result;
//    }



//    @RequestMapping("/chat")
//    public String chat(String message){
//        String result = model.chat(message);
//        return result;
//    }
}